<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0,user-scalable=no">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>抽奖</title>
  <link rel="stylesheet" href="main.css">
</head>
<body>
  <div class="writePriceNum" style="display:none">
    <h3>请输入中奖人数<span id="allPerson"></span></h3>
    <ul>
      <li><label for="xinyun">幸运奖：</label><input id="xinyun" min="1" type="number" /><span> 人</span></li>
      <li><label for="three">三等奖：</label><input id="three" min="1" type="number" /><span> 人</span></li>
      <li><label for="two">二等奖：</label><input id="two" min="1" type="number" /><span> 人</span></li>
      <li><label for="one">一等奖：</label><input id="one" min="1" type="number" /><span> 人</span></li>
      <li><label for="te">特等奖：</label><input id="te" min="1" type="number" /><span> 人</span></li>
    </ul>
    <div id="enterDraw" class="btn">确定</div>
  </div>
  <div class="container" style="display:none">
    <div class="left">
      <ul class="leftul">
        <li>
          <!-- <div>
            <img src="http://p0.meituan.net/avatar/1dff8c38406d4d6b6540c69503f409d357171.jpg" alt="">
            <span>张三</span>
          </div> -->
        </li>
      </ul>
    </div>
    <div class="right">
      <div class="rightContainer">
        <div class="productImg"><img src="./img/make.jpg" alt=""></div>
        <ul>
          <li>
            <div class="productDesc">
              <p>幸运奖：星巴克马克杯</p>
            </div>
            <!-- <div><img src="./img/2code.png" alt=""></div> -->
          </li>
        </ul>
        <div>
          <select id="select" class="" name="">
            <option value="all">参与人</option>
            <option value="幸运奖">幸运奖</option>
            <option value="三等奖">三等奖</option>
            <option value="二等奖">二等奖</option>
            <option value="一等奖">一等奖</option>
            <option value="特等奖">特等奖</option>
          </select>
          <div id="reset" class="btn">重置抽奖</div>
          <div style="clear:both"></div>
          <div id="clear" class="btn">清空</div>
          <div id="startStop" class="btn">开始</div>
        </div>
      </div>
    </div>
  </div>
  <script src="./js/src/jquery.min.js" charset="utf-8"></script>
  <script type="text/javascript">
    var yuming = 'http://hd.didadiandan.com';
    var html = "";
    var value = 0;
    var imgUrl = "https://ss0.bdstatic.com/94oJfD_bAAcT8t7mm9GUKT-xh_/timg?image&quality=100&size=b4000_4000&sec=1481508571&di=19d5d3251befcadd9fcfe33487ecf6f1&src=http://news.mydrivers.com/Img/20110518/04481549.png";
    var optionValue = "all";
    var drawInterval = "";
    var personToPicture = "";//扫描二维码上墙定时器
    var pubres = [];
    var res = [];
    var isDraw = false;//是否抽过奖
    var initArr = [{name:'???',image:imgUrl}];

    if(localStorage.te && localStorage.one && localStorage.two && localStorage.three && localStorage.xinyun) {
      $('.writePriceNum').hide();
      $('.container').show();
    }else {
      $('.writePriceNum').show();
      $('.container').hide();
    }
    //
    $('#enterDraw').click(function () {
      var xinyun = $('#xinyun').val();
      var three = $('#three').val();
      var two = $('#two').val();
      var one = $('#one').val();
      var te = $('#te').val();
      var totalInput = Number(xinyun)+Number(three)+Number(two)+Number(one)+Number(te);
      console.log(xinyun,three,two,one,te);
      console.log(value,totalInput);
      if(!xinyun || !three || !two || !one || !te) {
          alert("请填写完整的抽奖人数！");
          return false;
      }
      if(xinyun <= 0 || three <= 0 || two <= 0 || one <= 0 || te <= 0) {
        alert("抽奖人数必须为正整数！");
        return false;
      }
      // if(totalInput > value) {
      //   alert("您输入的中奖人数大于总的参与人数！");
      //   return false;
      // }

      localStorage.xinyun = xinyun;
      localStorage.three = three;
      localStorage.two = two;
      localStorage.one = one;
      localStorage.te = te;
      $('.writePriceNum').hide();
      $('.container').show();
      renderUserLists();//重置一次
    });
    //
    // 初始话渲染
    renderUserLists();
    personToPicture = setInterval(function () {
      console.log(1);
        renderUserLists();
    },10*1000);

    $('#select').on('change',function () {
      html = "";
      // console.log(this.options[this.options.selectedIndex].value);
      optionValue = this.options[this.options.selectedIndex].value;
      if(optionValue == "all") {
        personToPicture = setInterval(function () {
          console.log(1);
            renderUserLists();
        },10*1000);
      }else {
        clearInterval(personToPicture);
      }
      switch (optionValue) {
        case '幸运奖':
          value = Number(localStorage.xinyun);
          $('.productImg img').attr({'src':'./img/make.jpg'});
          $('.productDesc p').html('幸运奖：星巴克马克杯');
          break;
        case '三等奖':
          value = Number(localStorage.three);
          $('.productImg img').attr({'src':'./img/yashua.jpg'});
          $('.productDesc p').html('三等奖：电动牙刷');
          break;
        case '二等奖':
          value = Number(localStorage.two);
          $('.productImg img').attr({'src':'./img/wuyin.jpg'});
          $('.productDesc p').html('二等奖：无印良品香薰机');
          break;
        case '一等奖':
          value = Number(localStorage.one);
          $('.productImg img').attr({'src':'./img/kindle.jpg'});
          $('.productDesc p').html('一等奖：Kindle阅读器');
          break;
        case '特等奖':
          value = Number(localStorage.te);
          $('.productImg img').attr({'src':'./img/iphone7.jpg'});
          $('.productDesc p').html('特等奖：Iphone 7');
          break;
        default:
          value = userLists.length;
          $('.productImg img').attr({'src':'./img/make.jpg'});
          $('.productDesc p').html('幸运奖：星巴克马克杯');
          renderHtml(value,html,'userLists');
          return false;
      };
      checkHowToRender();
    });

    $('#startStop').click(function () {
      if(optionValue == "all") {
        alert("您选择抽奖等级！");
        return false;
      }
      if(isDraw) {
        alert("您已经抽过该奖项！");
        return false;
      }
      var content = $(this).html();
      if(content == "开始") {
        drawPrice();
        $(this).html("停止");
      }else {
        $.post(yuming+'/web/draw/start',{levelName:optionValue,num:value},function (data) {
            clearInterval(drawInterval);
            if(data.code == 100) {
                isDraw = true;
                res = data.object;
                // console.log(res);
                html = "";
                renderHtml(value,html,'res');
            }else {
              alert("抽奖无效："+data.message);
            }
        },"json");
        $(this).html("开始");
      }
    })

    $('#clear').click(function () {
      if(optionValue == "all") {
        alert("这是参与人，您不能清空！");
        return false;
      }
      var r = confirm("您确定要清空"+optionValue+"嘛？");
      if (r==true) {
        $.post(yuming+'/web/draw/clear',{levelName:optionValue},function (data) {
            if(data.code == 100) {
                isDraw = false;
                renderHtml(value,html,'pubres');
                alert("清除"+optionValue+"成功！");
            }else {
              alert(data.message);
            }
        },"json");
      }
    })
    $('#reset').click(function () {
      $.post(yuming+'/web/draw/clear',{},function (data) {
          if(data.code == 100) {
            var n = confirm("您确定要重置所有抽奖并重新输入抽奖人数嘛？")
            if(n) {
              localStorage.clear();
              window.location.reload();
            }
          }else {
            alert(data.message);
          }
      },"json");
    })

    function renderUserLists() {
      $.post(yuming+'/web/draw/list',{},function (data) {
          if(data.code == 100) {
              userLists = data.object;
              value = userLists.length;
              $('#allPerson').html('（共'+userLists.length+'人参与）')
              $('#select option').each(function (i,n) {
                // console.log(i,n);
                var content = ['参与人'+userLists.length+'人','幸运奖'+localStorage.xinyun+'人','三等奖'+localStorage.three+'人','二等奖'+localStorage.two+'人','一等奖'+localStorage.one+'人','特等奖'+localStorage.te+'人']
                $(n).html(content[i])
              });
              renderHtml(value,html,'userLists');
              // checkHowToRender();
          }else {
            alert(data.message);
          }
      },"json");
    }

    function renderHtml(value,html,type) {
      html = "";
      if(type == 'userLists') {//渲染全部用户信息
        for (var i = 0; i < userLists.length; i++) {
          html +=
          '<div>'+
            '<img src='+(userLists[i].image || imgUrl)+' alt="">'+
            '<span>'+userLists[i].name+'</span>'+
          '</div>'
        }
      }else if(type == 'pubres') {
        for (var i = 0; i < value; i++) {
          html +=
          '<div>'+
            '<img src='+initArr[0].image+' alt="">'+
            '<span>'+initArr[0].name+'</span>'+
          '</div>'
        }
      }else {
        for (var i = 0; i < value; i++) {
          // if(!res[i].hasOwnProperty('image')) {
          //   res[i].image = imgUrl;
          // }
          html +=
          '<div>'+
            '<img src='+(res[i].image || imgUrl)+' alt="">'+
            '<span>'+res[i].name+'</span>'+
          '</div>'
        }
      }
      $('.leftul li ').html(html);
    }

    function drawPrice() {
      var randomMax = userLists.length;
      drawInterval = setInterval(function () {
        html = "";
        for (var i = 0; i < value; i++) {
          var randomPerson = userLists[Math.floor(Math.random()*randomMax)];
          html +=
          '<div>'+
            '<img src='+(randomPerson.image || imgUrl)+' alt="">'+
            '<span>'+randomPerson.name+'</span>'+
          '</div>'
        }
        $('.leftul li').html(html);
      },100)
    }

    function checkHowToRender() {
      $.post(yuming+'/web/draw/view',{levelName:optionValue},function (data) {
          if(data.code == 100) {
              res = data.object;
              if(res.length == 0) {
                isDraw = false;
                renderHtml(value,html,'pubres');
              }else {
                for (var i = 0; i < res.length; i++) {
                  res[i].name = res[i].weixinName
                }
                // console.log(res);
                isDraw = true;
                html = "";
                renderHtml(res.length,html,'res');
              }
          }else {
            alert(data.message);
          }
      },"json");
    }
  </script>
</body>
</html>
